<template>
  <el-drawer
      size="30%"
      v-if="showDrawer"
      v-model="drawer"
      :title="formData.id?'修改酒店':'添加酒店'"
      direction="rtl"
      :before-close="closeDrawer">
    <el-form
      size="small"
      ref="formRef"
      :model="formData"
      status-icon
      :rules="rules"
      label-width="60px"
    >
      <!-- <el-form-item label="编号" prop="ID">
        <el-input v-model="formData.id" />
      </el-form-item> -->
      <el-form-item label="酒店名称" prop="hotelName">
        <el-input v-model="formData.hotelName" />
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-input v-model="formData.city" />
      </el-form-item>
      <el-form-item label="星级" prop="starRating">
        <el-input v-model="formData.starRating" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="formData.description" />
      </el-form-item>
      <el-form-item label="图片" prop="imageUrl">
        <el-upload
          class="avatar-uploader"
          limit="1"
          :auto-upload="false"

          :on-change="onSelectFile"

        >
          <el-icon class="avatar-uploader-icon">
            <Plus/>
          </el-icon>

          <el-image v-if="imgUrl" style="width: 60px; height: 60px" :src="imgUrl" fit="cover" />
        </el-upload>

      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">{{formData.id?'修改':'添加'}}</el-button>
        <el-button @click="resetForm(formRef)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<script setup lang="ts">
import request from '../../utils/request.js'
import {ref,reactive,watch} from 'vue'
import {ElNotification} from 'element-plus'
import {Plus} from '@element-plus/icons-vue'
// 导入element-plus的类型
import type { FormInstance, FormRules } from 'element-plus'
import {$add,} from '../../api/role.js'
import {$addHotel,$update} from '../../utils/request.js'






const emit = defineEmits(['sync-list'])
// 用于判断是否显示渲染抽屉的变量
const showDrawer = ref(false)
// 抽屉变量
const drawer = ref(false)
watch(drawer,(nval)=>{
  if(nval){
    showDrawer.value = true
  }else{
    setTimeout(() => {
      showDrawer.value = false
    }, 200)
  }
})

// 表单数据
let formData = ref({
  id: "",
  hotelName: "",
  city: "",
  starRating: "",
  description: "",
  imageUrl: ""
})

// 关闭抽屉
const closeDrawer = ()=>{
  drawer.value = false
  // 重置表单
  formRef.value?.resetFields()
  // 清空表单数据
  formData.value = {
  id: "",
  hotelName: "",
  city: "",
  starRating: "",
  description: "",
  imageUrl: ""
  }

  imagefile=null;
}


// 定义一个ref对象绑定表单
const formRef = ref<FormInstance>()

const imgUrl = ref('')
//图片文件
let imagefile:File
const onSelectFile = (uploadFile) => {
imgUrl.value = URL.createObjectURL(uploadFile.raw)
 imagefile=uploadFile.raw
 console.log(imgUrl.value)
}
// 验证角色名称
const validateRoleName = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入角色名称'))
  } else {
    callback()
  }
}
// 验证对象
const rules = reactive<FormRules<typeof formData>>({
  roleName: [{ validator: validateRoleName, trigger: 'blur' }]
})

//上传成功
const uploadSuccess: UploadProps['onSuccess'] = (response) => {
  let {filename,success} = response
  if(success){
    ElNotification({
      title: '提示',
      message: '头像上传成功',
      type: 'success',
    })
    // 获取头像地址
    formData.value.photo = filename
  }
}

// 上传之前
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 图片格式
  let imgTypes = ['image/jpeg','image/gif','image/png']
  if (!imgTypes.includes(rawFile.type)) {
    ElNotification({
      title: '提示',
      message: '请上传jpg,gif,png格式的图片',
      type: 'error',
    })
    return false
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElNotification({
      title: '提示',
      message: '图片大小不能超过1MB',
      type: 'error',
    })
    return false
  }
  return true
}



// 提交表单
const submitForm = (formEl: FormInstance | undefined) => {
  console.log(formData.value)
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      let ret = {}
      console.log(formData.value.imageUrl)
      // 判断是做修改还是添加
      if(formData.value.id){

        const formDat = new FormData();
        formDat.append('id',formData.value.id); // 通常应该从表单的其他输入字段中获取值
        formDat.append('hotelName',formData.value.hotelName); // 通常应该从表单的其他输入字段中获取值
        formDat.append('city',formData.value.city); // 同上
        formDat.append('starRating',formData.value.starRating); // 同上，或者从表单的<select>元素中获取
        formDat.append('description',formData.value.description); // 同上，从<textarea>中获取
        formDat.append('file',imagefile);
        const response =await $update('/hotel/update',formDat)
        ref.value=response
          console.log(ref.value)
      }else{

        const formDat = new FormData();
        formDat.append('hotelName',formData.value.hotelName); // 通常应该从表单的其他输入字段中获取值
        formDat.append('city',formData.value.city); // 同上
        formDat.append('starRating',formData.value.starRating); // 同上，或者从表单的<select>元素中获取
        formDat.append('description',formData.value.description); // 同上，从<textarea>中获取
        formDat.append('file',imagefile);
        const response =await $addHotel('/hotel/add',formDat)
        ref.value=response
        console.log(ref.value.code)

        // 重置表单
        formRef.value?.resetFields()

      }
      if(ref.value.code==200){
          ElNotification({
            title: '提示',
            message: ret.message,
            type: 'success',
          })
          // 通知父组件更新列表数据
          emit('sync-list')
        }else{
          ElNotification({
            title: '提示',
            message: ret.message,
            type: 'error',
          })
        }
    } else {
      return false
    }
  })
}

// 重置表单
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 暴露成员
defineExpose({
  drawer,
  formData
})

</script>
<style lang="scss" scoped>
.avatar-uploader-icon {
  width:200px;
  height:200px;
  background-color:gray
}
</style>
